import java.io.*;
import java.net.*;

// 服务器 构建
/*public class UdpEchoServer {
    private DatagramSocket socket=null;

    // 手动设置端口号
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    // 启动 服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //1. 接收请求 , 这里需要手动来申请一块内存来进行 存储 客户端的请求
            DatagramPacket requestPacket=new DatagramPacket(new byte[2048],2048);
            socket.receive(requestPacket);
            // 由于接收的为 字节流 ，需要手动将其转化为 字符流
            String request=new String(requestPacket.getData(),0,requestPacket.getLength());

            //2.做出响应
            String respond= process(request);

            //3.将响应 回馈给 客户端
            DatagramPacket respondPocket = new DatagramPacket(respond.getBytes(),respond.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(respondPocket);

            // 最后，选择通过日志的方式将 交互过程 打印出来
            System.out.printf("%s : %d , request: %s , respond: %s",requestPacket.getAddress().toString(),requestPacket.getPort(),
                    request  ,respond);

        }
    }

    private String process(String request) {
        return request;
    }


    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer=new UdpEchoServer(3465);
        udpEchoServer.start();
    }
}*/



public class UdpEchoServer{
    private DatagramSocket socket=null;

    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！！");
        while(true) {

            // 接收请求
            DatagramPacket requestPocket = new DatagramPacket(new byte[2048], 2048);
            socket.receive(requestPocket);

            String request = new String(requestPocket.getData(), 0, requestPocket.getLength());

            // 做出响应
            String respond = process(request);

            // 回馈给 客户端
            DatagramPacket respondPocket = new DatagramPacket(respond.getBytes(), respond.getBytes().length,
                    requestPocket.getSocketAddress());
            socket.send(respondPocket);

            System.out.printf("%s : %d , request: %s , respond: %s \n" , requestPocket.getAddress().toString(), requestPocket.getPort(),
                    request, respond);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(1245);
        server.start();
    }
}
